<script setup>
import { createProjectApi, findAllWorkGroupsApi, findSelfProjectApi, findUserByNameApi } from '@/apis/projectManagement'
import { onMounted, ref, watch } from 'vue'
import { useProjectManagementStore } from '@/store/createProjectDialog'
import { useProjectStore } from '@/store/project'
import { Delete as IconDelete, Plus as IconPlus, Search as IconSearch, User as IconUser } from '@element-plus/icons-vue'
import { ElLoading, ElMessage, genFileId } from 'element-plus'
import router from '@/router'
import avatarName from '@/components/avatarName'


const projectStore = useProjectStore()
const filePrefix = process.env.VUE_APP_BASE_URL
const createProjectRequest = ref({
  name: '',
  groupId: null,
  owner: null,
  description: '',
  file: null
})
const createProjectFormRef = ref(null)
const createProjectRules = ref({
  name: [
    {
      required: true, message: '请输入项目名称', trigger: 'blur',
    }
  ],
  owner: [
    {
      required: true, message: '请选择项目负责人', trigger: 'blur',
    }
  ],
  groupId: [
    {
      required: true, message: '请选择项目所属工作组', trigger: 'blur',
    }
  ],
  description: [
    {
      required: true, message: '请输入项目描述', trigger: 'blur',
    }
  ],
  file: [
    {
      required: true, message: '请上传项目封面图', trigger: 'blur',
    }
  ]
})
const projectManagementStore = useProjectManagementStore()
const projectImageFileRef = ref()
const workGroupList = ref([])
const ownerList = ref([])
const ownerSearchLoading = ref(false)
const selfProjectLoading = ref(true)
const selfProjectNameSearchTimeout = ref()
const selfProjectRequest = ref({
  name: '',
  pageNum: 1,
  pageSize: 10
})
const selfProjectResponse = ref({
  dataList: [],
  total: 0,
  pageNum: 1,
  pageSize: 10
})
const hiddenPagination = ref(true)

const onOwnerRemoteMethod = (name) => {
  ownerSearchLoading.value = true
  findUserByNameApi(name).then(({data}) => {
    ownerList.value = data || []
  }).finally(() => {
    ownerSearchLoading.value = false
  })
}

watch(() => projectManagementStore.createProjectDialogVisible, (n, o) => {
  if (o) return
  createProjectRequest.value.owner = null
  createProjectRequest.value.groupId = null
  createProjectRequest.value.name = ''
  createProjectRequest.value.description = ''
  createProjectRequest.value.file = null
  findAllWorkGroupsApi().then(({data}) => {
    workGroupList.value = data || []
  })
})

const findSelfProject = () => {
  selfProjectLoading.value = true
  findSelfProjectApi(selfProjectRequest.value.name, selfProjectRequest.value.pageNum, selfProjectRequest.value.pageSize).then(({data}) => {
    selfProjectResponse.value.total = data.total || 0
    selfProjectResponse.value.dataList = data.dataList || []
    selfProjectResponse.value.pageSize = data.pageSize || 10
    selfProjectResponse.value.pageNum = data.pageNum || 1
    hiddenPagination.value = selfProjectResponse.value.total <= selfProjectRequest.value.pageSize
  }).finally(() => {
    selfProjectLoading.value = false
  })
}

watch(() => selfProjectRequest.value.name, (n, o) => {
  if (selfProjectNameSearchTimeout.value) {
    clearTimeout(selfProjectNameSearchTimeout.value)
  }
  setTimeout(() => {
    findSelfProject()
  }, 300)
})

const onSelfProjectPageChange = (currentPage) => {
  selfProjectLoading.value = true
  selfProjectRequest.value.pageNum = currentPage
  findSelfProject()
}

// watch()

const onCreateProjectSubmit = async (formEl) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      const fd = new FormData()
      fd.append('name', createProjectRequest.value.name)
      fd.append('description', createProjectRequest.value.description)
      fd.append('groupId', createProjectRequest.value.groupId)
      fd.append('owner', createProjectRequest.value.owner)
      fd.append('file', createProjectRequest.value.file)
      const loading = ElLoading.service({
        lock: true
      })
      createProjectApi(fd).then(res => {
        ElMessage.success('项目创建成功！')
        findSelfProject()
        findSelfProjectApi().then(({data}) => {
          projectStore.myProject = data.dataList || []
        })
      }).finally(() => {
        loading.close()
        projectManagementStore.createProjectDialogVisible = false
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const onImageFileExceed = (files) => {
  const file = files[0]
  file.uid = genFileId()
  projectImageFileRef.value.clearFiles()
  projectImageFileRef.value.handleStart(file)
}

const onChangeImageFileUpload = (uploadFile) => {
  createProjectRequest.value.file = uploadFile.raw
}

const onHandleImageFileRemove = () => {
  createProjectRequest.value.file = null
  projectImageFileRef.value.clearFiles()
}

onMounted(() => {
  findSelfProject()
  findSelfProjectApi().then(({data}) => {
    projectStore.myProject = data.dataList || []
  })
})
</script>

<template>
  <el-breadcrumb separator="/" style="margin-bottom: 16px;">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>项目总览</el-breadcrumb-item>
  </el-breadcrumb>
  <div style="height: 100%; position: relative;" v-loading="selfProjectLoading">
    <div style="display: flex; justify-content: space-between; margin-bottom: 12px;">
      <div>
        <el-button @click="projectManagementStore.createProjectDialogVisible = true" :icon="IconPlus" type="primary"
                   size="small">新建
        </el-button>
      </div>
      <div>
        <el-input v-model="selfProjectRequest.name"
                  :prefix-icon="IconSearch"
                  placeholder="输入项目名称搜索"
                  size="small"
                  clearable
                  style="width: 168px"
        ></el-input>
      </div>
    </div>
    <div style="display: flex; flex-flow: wrap;">
      <el-empty style="margin: 128px auto 0" v-if="selfProjectResponse.dataList.length === 0"
                description="这里什么也没有~" />
      <el-card v-for="project in selfProjectResponse.dataList" :key="project.id" shadow="hover"
               style="width: 260px; margin: 0 12px 12px 0;  border-radius: 6px;"
               body-style="padding: 0; padding-bottom: 12px; cursor: pointer;">
        <template #header>
          <img
              :src="filePrefix + project.coverImgPath"
              style="width: 100%; height: 148px; object-fit: cover; object-position: center"
              alt="" />
        </template>
        <div style="padding: 28px 12px 12px;"
             @click="router.push(`/system/projectManagement/projectDetails?id=${project.id}`)">
          <div class="project-name">{{ project.name }}</div>
          <div class="project-owner">
            <el-icon>
              <icon-user />
            </el-icon>
            &ensp;项目负责人
          </div>
          <div style="margin: 12px 0 0 0; display: inline-block;">
            <div
                style="padding: 4px 12px 4px 6px; border-radius: 4px; background-color: #f0f1f5;">
              <avatar-name :url="project.owner.avatar ? filePrefix + project.owner.avatar : project.owner.name"
                           :name="project.owner.name" />
              <!--              <div v-if="project.owner.avatar">-->
              <!--                <img style="width: 20px; height: 20px; margin-right: 8px; border-radius: 50%"-->
              <!--                     :src="filePrefix + project.owner.avatar" alt=""/>-->
              <!--              </div>-->
              <!--              <div v-else-->
              <!--                   :style="`margin-right: 8px; padding: 3px 5px; border-radius: 50%; background-color: ${stringToColor((project.owner.name + '').charAt(0))}; font-size: 12px;`">-->
              <!--                <span style="color: #fff; line-height: 12px;">{{ (project.owner.name + '').charAt(0) }}</span>-->
              <!--              </div>-->
              <!--              <div style="font-size: 14px;">{{ project.owner.name }}</div>-->
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <div style="position: absolute; bottom: 0; width: 100%;">
      <div style="display: flex; align-items: center; justify-content: flex-end">
        <div style="margin-left: 16px">共{{ selfProjectResponse.total }}条</div>
        <el-pagination layout="prev, pager, next"
                       :total="selfProjectResponse.total"
                       :page-size="selfProjectRequest.pageSize"
                       @change="onSelfProjectPageChange"
                       :hide-on-single-page="hiddenPagination" />
      </div>
    </div>
  </div>

  <el-dialog v-model="projectManagementStore.createProjectDialogVisible" title="新建项目" width="700" draggable>
    <el-form :inline="true"
             ref="createProjectFormRef"
             :rules="createProjectRules"
             :model="createProjectRequest"
             label-position="top">
      <el-form-item label="项目名称" prop="name">
        <el-input style="width: 660px;" v-model="createProjectRequest.name" placeholder="输入项目名称" clearable />
      </el-form-item>
      <el-form-item label="项目负责人" prop="owner">
        <el-select
            v-model="createProjectRequest.owner"
            :remote-method="onOwnerRemoteMethod"
            placeholder="搜索负责人"
            :loading="ownerSearchLoading"
            style="width: 310px"
            clearable
            filterable
            remote
        >
          <el-option
              v-for="owner in ownerList"
              :key="owner.id"
              :label="owner.name"
              :value="owner.id"
          >
            <span style="float: left">{{ owner.name }}</span>
            <span
                style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
                {{ owner.username }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属工作组" prop="groupId" style="margin-right: 0">
        <el-select
            v-model="createProjectRequest.groupId"
            placeholder="选择项目所属工作组"
            style="width: 316px"
            clearable
        >
          <el-option v-for="group in workGroupList" :key="group.id" :label="group.gName" :value="group.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目描述" prop="description">
        <el-input style="width: 660px;"
                  :rows="4"
                  type="textarea"
                  v-model="createProjectRequest.description"
                  placeholder="描述下项目"
                  clearable />
      </el-form-item>

      <el-form-item label="项目封面图" prop="file">
        <el-upload action="#"
                   :limit="1"
                   :on-exceed="onImageFileExceed"
                   :on-change="onChangeImageFileUpload"
                   ref="projectImageFileRef"
                   list-type="picture-card" accept=".png,.jpeg,.jpg"
                   :auto-upload="false">
          <el-icon>
            <icon-plus />
          </el-icon>

          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              <span class="el-upload-list__item-actions">
            <span
                class="el-upload-list__item-delete"
                @click="onHandleImageFileRemove"
            >
              <el-icon><icon-delete /></el-icon>
            </span>
          </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" size="small" @click="projectManagementStore.createProjectDialogVisible = false">取消
        </el-button>
        <el-button type="primary" size="small" @click="onCreateProjectSubmit(createProjectFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="less">
:deep(.el-card__header) {
  padding: 0;
}

.project-name {
  font-size: 18px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.project-owner {
  margin-top: 12px;
  display: flex;
  align-items: center;
}

:deep(.el-textarea__inner) {
  resize: none;
}

:deep(.el-dialog) {
  border-radius: 4px !important;
}

</style>